package com.bakend.common.config.security.login;

import com.bakend.modules.sys.entity.User;
import com.bakend.modules.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomerUserDetailService implements UserDetailsService {

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //获取用户信息
        User user = userService.getUserByUserCode(userName);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        CustomerUserDetails customerUserDetails = new CustomerUserDetails(user);

        //查询权限，也可以权限信息不在这里查，权限信息单独弄个接口（前后端分离情况下，让前端自己查询菜单的权限，资源的权限由服务器控制）
//        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
//        if (CollectionUtils.isNotEmpty(customerUserDetails.getRoles())){
//            user.getRoles().forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_"+r.getRoleName())));
//        }
//        customerUserDetails.setAuthorities(authorities);
//        log.info("authorities:{}", JSON.toJSONString(authorities));
        //这里返回的是我们自己定义的UserDetail
        return customerUserDetails;
    }
}
